package com.she.olympic;

import ken.app.bean.UpdPushTokenBean;
import ken.app.even.Event;
import ken.app.even.KenEventManager;
import ken.app.even.UpdPushTokenEvent;
import ken.app.even.iface.IEventCallback;
import com.she.olympic.R;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class C2DMReceiver extends BroadcastReceiver {
	// Log Tag
	private static final String TAG = C2DMReceiver.class.getSimpleName();
    // Extras in the registration callback intents.
    public static final String EXTRA_UNREGISTERED 	= "unregistered";
    public static final String EXTRA_ERROR			= "error";
    public static final String EXTRA_REGISTRATION_ID 	= "registration_id";

    private NotificationManager notificationManager;
    
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
        if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
        	handleRegistration(context, intent);
        } else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
        	handleMessage(context, intent);
        } else if (intent.getAction().equals("com.google.android.c2dm.intent.RETRY")) {
        	context.startService(new Intent(C2DMRegService.REGISTER_ACTION));
        } else {
            Log.w(TAG, "Unexpected intent: " + intent);
        }
	}
	
    private void handleRegistration(final Context context, Intent intent) {
        String RegistrationId 	= intent.getStringExtra(EXTRA_REGISTRATION_ID);
        String Error 			= intent.getStringExtra(EXTRA_ERROR);
        String Removed  		= intent.getStringExtra(EXTRA_UNREGISTERED);
        
        this.getApp(context).setProcessing(false);
        
        if (Error != null) {
        	
        	if (this.getApp(context).IsDebuggable())
        		Log.w(TAG, "Registration failed: " + Error);
        	
        	// error & disable push...
        	// clear registration id first...(avoid to run C2DMRegService.UNREGISTER_ACTION)
        	this.getApp(context).setRegistrationID("");
        	this.getApp(context).enablePush(false);
        	
        	if (Error.equals("SERVICE_NOT_AVAILABLE")) {
        		long backoffTimeMs = 30000;
        		Intent retryIntent = new Intent("com.google.android.c2dm.intent.RETRY");
        		PendingIntent retryPIntent = PendingIntent.getBroadcast(context, 0, retryIntent, 0);
        		
        		AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);  
                am.set(AlarmManager.ELAPSED_REALTIME, backoffTimeMs, retryPIntent);
        	}
        	
            

        } else if (RegistrationId != null) {
        	
        	if (this.getApp(context).IsDebuggable())
                Log.d(TAG, "Registered with registration ID [" + RegistrationId + "]");
        	// Save registration id to preference...
        	
        	Log.d("ken", "RegistrationId "+RegistrationId);
        	
        	//TODO 抓到RegistrationId丟給API
    		UpdPushTokenEvent updPushTokenEvent = new UpdPushTokenEvent(null , RegistrationId);
    		updPushTokenEvent.addCallback(new IEventCallback() {
    			
    			@Override
    			public void result(Event event, Object result) {
    				// TODO Auto-generated method stub
    				if (result instanceof UpdPushTokenBean) {
	    				if (((UpdPushTokenBean)result).getResult() == 0000) {
		    				Log.d("ken", "updPushTokenEvent開啟成功");
		    				C2DMReceiver.this.getApp(context).setRegistrationID(((UpdPushTokenEvent)event).getRegid());
						}
					}else if (result == null) {
						Log.d("ken", "updPushTokenEvent開啟失敗");
					}

    			}
    			
    			@Override
    			public void progress(Event event, int progress, String tmpPath) {
    				// TODO Auto-generated method stub
    				
    			}
    		});
    		KenEventManager.getInstance().execute(updPushTokenEvent);
        	
        	
        } else if (Removed != null) {
        	
        	if (this.getApp(context).IsDebuggable())
        		Log.w(TAG, "Unregistration!!");
        	// Save to preference...
        	this.getApp(context).setRegistrationID("");
        	if (this.getApp(context).isPushEnabled()==true)
        		this.getApp(context).enablePush(false);
        	
        } else {
        	Log.d(TAG, "Other registration response: " + intent.getExtras());
        }
    }
    
    private void handleMessage(Context context, Intent intent) {
        Log.d(TAG, "Handling C2DM notification");
        
     	String pushMessage = intent.getExtras().getString("payload");//推播訊息
     	String temp2 = intent.getExtras().getString("pid");
     	Log.e("ken", "收到推播通知 "+ pushMessage +"-"+ temp2); 
        // need implementation...
        //TODO SHOW東西在狀態列 並點級開啟APP
        //=================Notification============================
        Intent it = new Intent(context, TreeActivity.class);
     	
        /*推播需傳送資料時*/
//     	if ((pushMessage.substring(3, 5)).equals("") == false) {
     		Bundle bundle = new Bundle();
//     		String temp = pushMessage.replaceAll("的果實即將成熟，準備採果囉！", "");
//     		temp = pushMessage.replaceAll("選手", "");
//     		bundle.putString("treeName", temp);
     		bundle.putBoolean("pushIn", true);
     		it.putExtras(bundle);
//     		temp = null;
//		}
     	
        it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//      it.setData(Uri.parse("http://tw.yahoo.com"));
        PendingIntent contentIntent =PendingIntent.getActivity(context, 0, it, 0);
        notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        
 
        
        Notification notification = new Notification();
        notification.icon = R.drawable.ic_launcher;
        notification.tickerText = "中華加油照集令-採果通知";
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.setLatestEventInfo(context, "中華加油照集令-採果通知", pushMessage, contentIntent);
        notificationManager.notify(0, notification);
        pushMessage = null;
        temp2 = null;
        //==========================================================
    }
    
    private Olympic getApp(Context context) {
        return (Olympic)context.getApplicationContext();
    }

}
